package com.yuma.tingshu.payment.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.github.binarywang.wxpay.bean.notify.WxPayNotifyV3Result;
import com.yuma.tingshu.account.client.RechargeInfoFeignClient;
import com.yuma.tingshu.common.constant.RabbitConstant;
import com.yuma.tingshu.common.constant.SystemConstant;
import com.yuma.tingshu.common.execption.YumaException;
import com.yuma.tingshu.common.result.Result;
import com.yuma.tingshu.common.result.ResultCodeEnum;
import com.yuma.tingshu.model.account.RechargeInfo;
import com.yuma.tingshu.model.order.OrderInfo;
import com.yuma.tingshu.model.payment.PaymentInfo;
import com.yuma.tingshu.order.client.OrderInfoFeignClient;
import com.yuma.tingshu.payment.mapper.PaymentInfoMapper;
import com.yuma.tingshu.payment.service.PaymentInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.Date;

@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class PaymentInfoServiceImpl extends ServiceImpl<PaymentInfoMapper, PaymentInfo> implements PaymentInfoService {

    @Autowired
    private PaymentInfoMapper paymentInfoMapper;

    @Resource
    private OrderInfoFeignClient orderInfoFeignClient;

    @Resource
    private RechargeInfoFeignClient rechargeInfoFeignClient;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Transactional
    @Override
    public void updatePaymentStatus(WxPayNotifyV3Result.DecryptNotifyResult result) {
        // 1.获取out_trade_no 回调微信返回的外部订单号
        PaymentInfo paymentInfo = paymentInfoMapper.selectOne(new LambdaQueryWrapper<PaymentInfo>()
                .eq(PaymentInfo::getOrderNo, result.getOutTradeNo()));
        // 2.没有对象抛异常
        if (paymentInfo == null) {
            throw new YumaException(ResultCodeEnum.PAYMENT_NOT_EXIST);
        }
        // 3.从result结果对象中拿属性设置给payment那些回调属性
        paymentInfo.setOutTradeNo(result.getTransactionId());
        paymentInfo.setPaymentStatus(SystemConstant.PAYMENT_STATUS_PAID);
        paymentInfo.setCallbackTime(new Date());
        paymentInfo.setCallbackContent(JSON.toJSONString(result));
        // 4.更新payment对象
        if (paymentInfoMapper.updateById(paymentInfo) == 1) {
            // 两个业务：订单业务，充值业务
            // 5.更新orderInfo的订单状态
            if (SystemConstant.PAYMENT_TYPE_ORDER.equals(paymentInfo.getPaymentType())) {
                rabbitTemplate.convertAndSend(RabbitConstant.ORDER_EXCHANGE, RabbitConstant.ORDER_PAID_RK, paymentInfo.getOrderNo());
            } else if (SystemConstant.PAYMENT_TYPE_RECHARGE.equals(paymentInfo.getPaymentType())) {
                // 充值业务，发送充值消息队列
                rabbitTemplate.convertAndSend(RabbitConstant.ORDER_EXCHANGE, RabbitConstant.RECHARGE_PAID_RK, paymentInfo.getOrderNo());
            }
        } else {
            // TODO 更新对账表失败，走退账流程
        }
    }

    @Transactional
    @Override
    public PaymentInfo savePaymentInfo(String paymentType, String orderNo) {
        // 1.先判空
        if (StringUtils.isBlank(orderNo) || StringUtils.isBlank(paymentType)) {
            return null;
        }
        // 2.直接根据orderNo查询是否存在此支付信息，如果存在，则直接返回
        PaymentInfo paymentInfo = paymentInfoMapper.selectOne(new LambdaQueryWrapper<PaymentInfo>()
                .eq(PaymentInfo::getOrderNo, orderNo));
        if (paymentInfo != null) {
            return paymentInfo;
        }

        paymentInfo = new PaymentInfo();
        // 3.根据paymentType： 1.普通业务 OrderInfo表  2.充值业务 RechargeInfo表不一样
        if (SystemConstant.PAYMENT_TYPE_ORDER.equals(paymentType)) { // 订单
            // 去查询OrderInfo表
            Result<OrderInfo> orderInfoResult = orderInfoFeignClient.getOrderInfo(orderNo);
            Assert.notNull(orderInfoResult, "订单不存在");
            OrderInfo orderInfo = orderInfoResult.getData();

            paymentInfo.setPaymentType(SystemConstant.PAYMENT_TYPE_ORDER);
            paymentInfo.setAmount(orderInfo.getOrderAmount());
            paymentInfo.setContent(orderInfo.getOrderTitle());
            paymentInfo.setPayWay(orderInfo.getPayWay());
            paymentInfo.setUserId(orderInfo.getUserId());
        } else {   // 充值业务
            // 去查询RechargeInfo表
            Result<RechargeInfo> rechargeInfoResult = rechargeInfoFeignClient.getRechargeInfo(orderNo);
            Assert.notNull(rechargeInfoResult, "充值订单不存在");
            RechargeInfo rechargeInfo = rechargeInfoResult.getData();

            paymentInfo.setPaymentType(SystemConstant.PAYMENT_TYPE_RECHARGE);
            paymentInfo.setAmount(rechargeInfo.getRechargeAmount());
            paymentInfo.setContent("充值" + rechargeInfo.getRechargeAmount() + "元");
            paymentInfo.setPayWay(rechargeInfo.getPayWay());
            paymentInfo.setUserId(rechargeInfo.getUserId());
        }
        paymentInfo.setOrderNo(orderNo);
        paymentInfo.setPaymentStatus(SystemConstant.PAYMENT_STATUS_UNPAID);
        // 4.保存支付信息
        paymentInfoMapper.insert(paymentInfo);
        return paymentInfo;
    }
}
